var contentObj = {};
contentObj.kq_data = [];

// 封装 chrome.storage.local.get 为 Promise
contentObj.getData = function (key_list) {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get(key_list, function (result) {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
    });
}

contentObj.getNowTime = function () {
    var now = new Date();
    var options = {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    };

    shanghaiDate = now.toLocaleDateString('zh-CN', options).replace(/\//g, '-');
    return shanghaiDate;
}


// 在页面完全加载后执行
if (document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll)) {
    init();
} else {
    document.addEventListener('DOMContentLoaded', init);
}

function init() {
    // 这一名与eventPage.js中通信，实现插件图标变亮
    chrome.runtime.sendMessage({ todo: "showPageAction" });

    // 下面监听来自popup.js发的消息，并修改web页面
    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
        if (request.todo == "saveReference") {
            var title = document.title;
            title = title.substr(title.indexOf(')') + 1, title.length).trim();
            var rf = window.location.href + " (" + title + ")";
            copyToClip(rf);
        }
    });

    // 确认页面完全加载
    if (document.readyState === 'complete') {
        console.log('Document is fully loaded.');
    } else {
        console.log('Document is still loading...');
        // 使用 setTimeout 确保页面完全加载
        setTimeout(init, 100);
        return;
    }

    // 检查页面中是否已有 jQuery
    if (window.jQuery) {
        console.log('jQuery 已经加载:', jQuery.fn.jquery); // 输出 jQuery 版本号
        executeAjax();
    } else {
        console.log('jQuery 未加载');
        // 如果需要重新加载 jQuery，可以在这里添加代码
        // 但是通常情况下不需要这样做，除非页面中没有 jQuery

        // 引入 jQuery
        var script = document.createElement('script');
        script.src = chrome.runtime.getURL('jquery-3.1.0.min.js');
        (document.head || document.documentElement).appendChild(script);

        // 在 jQuery 加载完成后执行
        script.onload = function () {
            executeAjax();
        }
    }
}

/**
 * 获取当前年月和上一个年月的信息。
 * @return {Array<string>} 一个包含两个字符串的数组，第一个字符串是当前年月，第二个字符串是上一个年月。
 * 
 */
function getCurrentAndPreviousMonth() {
    const now = new Date();
    const currentYear = now.getFullYear();
    let currentMonth = now.getMonth(); // getMonth() 返回的月份是从 0 开始的，所以需要加 1
    currentMonth += 1;

    // 计算上一个年月
    let previousYear = currentYear;
    let previousMonth = currentMonth - 1;

    if (previousMonth === 0) {
        previousMonth = 12;
        previousYear -= 1;
    }

    // 格式化年月信息
    const currentFormatted = `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}`;
    const previousFormatted = `${previousYear}-${previousMonth < 10 ? '0' + previousMonth : previousMonth}`;

    return [currentFormatted, previousFormatted];
}

/**
 * 获取指定月份的考勤异常信息
 * @param {*} date_str 
 */
function getMonthKQInfo(date_str) {
    return new Promise((resolve, reject) => {
        console.log('date_str: ' + date_str);
        const currentOrigin = window.location.origin;
        const apiUrl = `${currentOrigin}/api/kq/myattendance/getHrmKQMonthReportInfo`;

        // 发起POST请求
        $.ajax({
            url: apiUrl,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
                // 'Cookie': 'your-cookie-data',  // 替换为实际的cookie
                'X-Requested-With': 'XMLHttpRequest'
            },
            data: {
                typevalue: date_str,
                loaddata: '1',
                type: '2'
            },
            success: function (response) {
                let response_str = response;
                let json_obj = JSON.parse(response_str);

                // 查找考勤异常的信息
                let filteredList = [];
                let formattedStrings = '';
                const result = json_obj.result;
                for (const key in result) {
                    if (result.hasOwnProperty(key)) {
                        const item = result[key];
                        if (item.isWorkDay && item.types.length > 0 && item.types[0] !== 'NORMAL') {
                            filteredList.push(item);
                            if (contentObj.kq_handle_obj != undefined && item.date in contentObj.kq_handle_obj &&
                                contentObj.kq_handle_obj[item.date] === '已处理') {
                                continue;
                            }
                            // 拼接日期与type
                            const typeStr = item.types.length > 0 ? item.types[0] : "无类型";
                            const formattedStr = `${item.date}: ${typeStr}`;
                            formattedStrings += '; ' + formattedStr;
                        }
                    }
                }

                console.log(filteredList);
                if (filteredList.length > 0) {
                    contentObj.kq_data = contentObj.kq_data.concat(filteredList);
                }
                formattedStrings = formattedStrings.substring(2);
                // console.log(formattedStrings);
                if (formattedStrings.length > 0) {
                    console.log(formattedStrings);
                    alert(formattedStrings);
                } else {
                    console.log(date_str + ' is ok~~~~~~');
                }
                resolve(); // 成功时解析 Promise
            },
            error: function (xhr, status, error) {
                console.error('Error:', error);
                reject(error); // 失败时拒绝 Promise
            }
        });
    });
}


async function executeAjax() {
    const [currentMonth, previousMonth] = getCurrentAndPreviousMonth();

    let result = await contentObj.getData(['kq_handle_obj']);
    contentObj.kq_handle_obj = result.kq_handle_obj;

    // 清除旧的异常考勤数据
    contentObj.kq_data.length = 0;
    await getMonthKQInfo(previousMonth);
    await getMonthKQInfo(currentMonth);

    // 存储脚本最新的运行时间，标识脚本是否已运行过
    let query_kq_time = contentObj.getNowTime();
    // 使用自定义键名存储数据
    chrome.storage.local.set({ kq_data: contentObj.kq_data, query_kq_time: query_kq_time }, function () {
        console.log('kq_data has been saved locally.');
    });
}

/**
 * 复制单行内容到粘贴板
 * @param {string} content - 需要复制的内容
 * @param {string} [message="复制成功"] - 复制完后的提示，默认提示"复制成功"
 */
function copyToClip(content, message = "复制成功") {
    var aux = document.createElement("input");
    aux.setAttribute("value", content);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
    document.body.removeChild(aux);
    // alert(message);
}